package com.kjsdfgk.hjmdsf.member.mvp.presenter;

import android.app.Application;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;

import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;

import javax.inject.Inject;

import com.jess.arms.utils.RxLifecycleUtils;
import com.kjsdfgk.hjmdsf.app.App;
import com.kjsdfgk.hjmdsf.app.entity.Account;
import com.kjsdfgk.hjmdsf.app.entity.AccountJson;
import com.kjsdfgk.hjmdsf.app.entity.RegJson;
import com.kjsdfgk.hjmdsf.app.entity.ResultJson;
import com.kjsdfgk.hjmdsf.member.mvp.contract.MemberCenterContract;
import com.kjsdfgk.hjmdsf.member.mvp.ui.activity.MemberCenterActivity;
import com.lksdkjs.live.R;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.TreeMap;

import static com.jess.arms.utils.ArmsUtils.startActivity;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 04/15/2020 11:11
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@ActivityScope
public class MemberCenterPresenter extends BasePresenter<MemberCenterContract.Model, MemberCenterContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    @Inject
    public MemberCenterPresenter(MemberCenterContract.Model model, MemberCenterContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }
    String type = "alipay";
    String name = "vip7";
    float money = 3f;
    public void payMemBer(int id) {
        switch (id) {

            case R.id.member_center_v1_cv:

                money = 1f;
                name = "会员周卡_1822";

                break;
            case R.id.member_center_v2_cv:
                money = 6f;
                name = "会员月卡_1822";

                break;
            case R.id.member_center_v3_cv:
                money = 14.9f;
                name = "会员季卡_1822";

                break;
            case R.id.member_center_v4_cv:
                money = 29.9f;
                name = "会员年卡_1822";

                break;
        }

        mRootView.showPayDlg();
    }

    public void goAppToPay(String payType) {
        String url = getAppPay(payType);
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
         startActivity(intent);
    }


    private String getAppPay(String type) {
        String out_trade_no = "live3ca369f50f8b2281";
        if (TextUtils.isEmpty(out_trade_no)) out_trade_no = "20200215192301229";
        TreeMap<String, String> map = new TreeMap();
        map.put("pid", "10056");
        map.put("type", type);
        map.put("out_trade_no", out_trade_no);
        map.put("notify_url", "http://www.lailujuan.com/notify.html");
        map.put("return_url", "http://www.lailujuan.com/index.html");
        map.put("name", name);
        map.put("money", String.valueOf(money));
        map.put("sitename", "www.lailujuan.com");

        StringBuilder sb = new StringBuilder();
        for (String k : map.keySet()) {
            sb.append("&" + k + "=" + map.get(k));
        }
        sb.append("Rx6r5KS5mzpHi7YmRBNR4kQF5Sm4Aktw");
        String sign = md5Decode32(sb.toString().replaceFirst("&", ""));
        String url = "https://pay.muitc.com/submit.php?pid=10056&type=" + type + "&out_trade_no=" + out_trade_no + "&notify_url=http://www.lailujuan.com/notify.html&return_url=http://www.lailujuan.com/index.html&" +
                "name=" + name + "&money=" + money + "&sitename=www.lailujuan.com&sign=" + sign + "&sign_type=MD5";


        return url;

    }

    public String md5Decode32(String content) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(content.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("NoSuchAlgorithmException", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("UnsupportedEncodingException", e);
        }
        //对生成的16字节数组进行补零操作
        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10) {
                hex.append("0");
            }
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }

    public Account getAccount() {

       return (Account) ((App)mApplication).getAppComponent().extras().get("Account");
    }

    public void getGoods() {

        Account account = getAccount();

        mModel.cardCharge( account.getToken() ,"1MQkso3Yfq" )
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(3, 2))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .subscribe(new ErrorHandleSubscriber<ResultJson>(mErrorHandler) {
                    @Override
                    public void onError(@NonNull Throwable e) {

                        mRootView.hideLoading();
                        mRootView.showMessage(e.toString());

                    }

                    @Override
                    public void onNext(@NonNull ResultJson goodsJson) {
                        mRootView.showMessage(goodsJson.getMsg());
                    }
                });
    }
}
